package com.itcast.controller;

import com.itcast.pojo.Book;
import com.itcast.pojo.BorrowedQuantity;
import com.itcast.pojo.PageBean;
import com.itcast.pojo.Result;
import com.itcast.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;

    /**
     * 查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping
    public Result findBooks(@RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "5") Integer pageSize) {
        PageBean pageBean = bookService.findBooks(page, pageSize);
        return Result.success(pageBean);
    }

    /**
     * 新增图书
     * @param book
     * @return
     */
    @PostMapping
    public Result add(@RequestBody Book book) {
        bookService.add(book);
        return Result.success();
    }

    /**
     * 根据id查询图书信息（回显）
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id){
        Book book = bookService.findById(id);
        return Result.success(book);
    }

    /**
     * 修改图书信息
     * @param book
     * @return
     */
    @PutMapping
    public Result set(@RequestBody Book book){
        bookService.set(book);
        return Result.success();
    }

    /**
     * 删除图书信息（非管理员无权限删除）
     * @param id
     * @param request
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id, HttpServletRequest request){
        String token = request.getHeader("token");
        Integer sign = bookService.delete(id,token);
        if (Objects.equals(sign,0)){
            return Result.error("权限不足");
        }
        return Result.success();
    }

    /**
     * 统计图书借阅情况
     * @return
     */
    @GetMapping("/count")
    public Result count(){
        List<BorrowedQuantity> borrowedQuantity = bookService.group();
        return Result.success(borrowedQuantity);
    }
}
